package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty

class Biquw : BaseBookHandler() {
    override val host: String
        get() = "www.biquw.la"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val coverImageUrl = document.metaContentWithProperty("og:image")
        return BookMetaEntity(name, url, url, author, coverImageUrl)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val elements = document.select("div.book_list > ul > li > a")
        return elements.mapIndexed { index, element ->
            val name = element.text().trim()
            val link = menuUrl.toHttpUrl().resolve(element.attr("href"))
            ChapterMetaEntity(name, index, link.toString(), element)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val url = chapterMetaEntity.url
        val doc = url.toHttpUrl().toDocument() ?: return null
        val text = doc.select("#htmlContent")[0].bookText()
        return ChapterEntity(chapterMetaEntity.name, chapterMetaEntity.index, text)
    }
}